package lib

import (
	"errors"
	"gin/config"

	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"github.com/sirupsen/logrus"
)

var MinIOMapPool map[string]*MinIoClientConf

type MinIoClientConf struct {
	Client      *minio.Client
	AllowBucket []string
	Endpoint    string
	UseSSL      bool
}

// InitMinIO 初始化MinIO
func InitMinIO() error {
	MinIOMapPool = map[string]*MinIoClientConf{}
	for n, c := range config.MinIO {
		minioClient, err := minio.New(c.Endpoint, &minio.Options{
			Creds:  credentials.NewStaticV4(c.AccessKeyID, c.SecretAccessKey, ""),
			Secure: c.UseSSL,
		})

		if err != nil {
			return err
		}

		MinIOMapPool[n] = &MinIoClientConf{Client: minioClient, AllowBucket: c.AllowBucket, Endpoint: c.Endpoint, UseSSL: c.UseSSL}
		logrus.Infof("%s MinioClient pool start", n)

	}

	return nil
}

func GetMinIOClient(name string) (*MinIoClientConf, error) {
	if c, ok := MinIOMapPool[name]; ok {
		return c, nil
	}
	return nil, errors.New("get minio conf error")
}

// GetMinIODefaultConf 获取默认配置
func GetMinIODefaultConf() (*MinIoClientConf, error) {
	return GetMinIOClient("default")
}
